/*  basic function  */

import Cookies from 'js-cookie'
import gcoord from 'gcoord'

export default function () {
  let o = {
    // 获取文档宽度
    getDocumentWidth () {
      return document.documentElement.clientWidth || document.body.clientWidth
    },

    // 获取文档高度
    getDocumentHeight () {
      return document.documentElement.clientHeight || document.body.clientHeight
    },

    // cookie操作
    setCookies (key, val, config) {
      Cookies.set(key, val, config)
    },

    getCookies (key) {
      Cookies.get(key)
    },

    delCookies (key) {
      Cookies.remove(key)
    },

    // localStorage封装
    setLocalStorage (key, data) {
      let storage = window.localStorage
      let myData = data
      if (typeof myData === 'object' || typeof myData === 'function') {
        storage.setItem(key, JSON.stringify(myData))
      } else {
        storage.setItem(key, myData)
      }
      return myData
    },

    getLocalStorage (key) {
      let storage = window.localStorage
      return storage.getItem(`Standard__${key}`)
    },

    // sessionStorage封装
    setSessionStorage (key, data) {
      let storage = window.sessionStorage
      let myData = data
      if (typeof myData === 'object' || typeof myData === 'function') {
        storage.setItem(key, JSON.stringify(myData))
      } else {
        storage.setItem(key, myData)
      }
      return myData
    },

    getSessionStorage (key) {
      let storage = window.sessionStorage
      return storage.getItem(key)
    },

    // 计算当前时间的时间差
    timeConvert (timeValue) {
      let date1 = timeValue // 开始时间
      let date2 = new Date() // 结束时间
      let date3 = date2.getTime() - new Date(date1).getTime() // 时间差的毫秒数
      // 计算出相差天数
      let days = Math.floor(date3 / (24 * 3600 * 1000))
      // 计算出小时数
      let leave1 = date3 % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
      let hours = Math.floor(leave1 / (3600 * 1000))
      // 计算相差分钟数
      let leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
      let minutes = Math.floor(leave2 / (60 * 1000))
      // 计算相差秒数
      let leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
      let seconds = Math.round(leave3 / 1000)
      let showTime = ''
      if (days >= 0) {
        showTime = days + '天 ' + hours + '小时' + minutes + '分'
      } else if (days < 0 || hours < 0 || minutes < 0 || seconds < 0) {
        showTime = '-'
      }
      return showTime
    },

    // 个位数转化为'0x'形式
    singleAddZero (num) {
      return num < 10 ? '0' + num : num
    },

    // date转化为string(yyyy-MM-dd hh-mm-ss)
    dateToString (newDate) {
      let tDate = newDate
      if (!tDate) {
        tDate = new Date()
      }
      let yyyy = tDate.getFullYear()

      let MM = this.singleAddZero(tDate.getMonth() + 1)

      let dd = this.singleAddZero(tDate.getDate())

      let hh = this.singleAddZero(tDate.getHours())

      let mm = this.singleAddZero(tDate.getMinutes())

      let ss = this.singleAddZero(tDate.getSeconds())
      return yyyy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
    },

    // 生成随机字符串
    randomString (len) {
      len = len || 32
      const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789'
      const maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },

    // echarts字体转化
    /**
     *
     * @param size
     * @returns {number}
     */
    transFontSizeECharts (size) {
      // console.log('document.documentElement.style.fontSize', document.documentElement.style.fontSize.slice(0, -2))
      return (size / 100) * document.documentElement.style.fontSize.slice(0, -2)
    },
    /**
     * 随机整数
     * @param min 最小
     * @param max 最大
     * @param num 有此数就随机生成一个指定长度的数组
     * @returns {number}
     */
    mathRandom (min, max, num) {
      if (num) {
        let tempArr = []
        for (let i = 0; i < num; i++) {
          tempArr.push(Math.floor(Math.random() * (max - min + 1) + min))
        }
        return tempArr
      } else {
        return Math.floor(Math.random() * (max - min + 1) + min)
      }
    },
    // 地图坐标转换
    transCoordinate (lng, lat, type = 0, newType = 0) {
      const obj = {
        0: gcoord.AMap, // GCJ-02
        1: gcoord.BMap, // BD-09
        2: gcoord.WGS84, // WGS84
        3: gcoord.WebMercator // Web Mercator投影，墨卡托投影
      }
      let old = [lng, lat]
      return gcoord.transform(old, obj[type], obj[newType])
    },
    // 全局formatter方法
    constFormatter (constant, val) {
      let res = ''
      constant.forEach(item => {
        if (item.value === val) {
          res = item.label
        }
      })
      return res
    },
    // 获取用户信息
    getUserInfo () {
      return this.getLocalStorage('zjUserInfo') ? JSON.parse(this.getLocalStorage('zjUserInfo')) : {}
    },
    // 获取接口权限
    getUserApiPermission () {
      return this.getUserInfo()['authApiPermissions'] || []
    },
    // 获取页面权限
    getUserPagePermission () {
      return this.getUserInfo()['authPagePermissions'] || []
    },
    // 生成首页路由
    generateIndexRouter (data) {
      let indexRouter = []
      return [...indexRouter, ...this.generateChildRouters(data)]
    },

    // 生成嵌套路由（子路由）
    generateChildRouters (data) {
      const routers = []
      for (var item of data) {
        let hasChildren = item.children && item.children.length
        if (item.parentId === '0') {
          item.name = item.menuName
          item.url = item.menuRoute
          item.frontPath = 'Layout/AppContent'
        }
        item.redirect = hasChildren ? item.children[0].url : ''
        let component = 'views/' + item.frontPath
        let menu = {
          path: item.url,
          name: item.url,
          hidden: item.isEnable === 0,
          redirect: item.redirect,
          component: resolve => require(['@/' + component + '.vue'], resolve),
          meta: {
            title: item.name,
            icon: item.picUrl,
            url: item.thdUrl
          }
        }
        if (hasChildren > 0) {
          menu.children = [...this.generateChildRouters(item.children)]
        }
        routers.push(menu)
      }
      return routers
    }
  }
  return o
}
